import { useSettingStore } from '@/stores'
import type { settingItem } from '@/types/home'
import { request } from '@/utils/request'

// 获取系统配置
export const getSettingApi = () => {
  return request<settingItem>({
    method: 'GET',
    url: '/common/setting',
  })
}

/**
 * 上传
 * @param filePath
 * @returns
 */
export const uploadApi = (filePath: string): Promise<AnyObject> => {
  const uploadSetting = useSettingStore().data.upload_setting

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `/common/upload?driver=${uploadSetting.mode}`,
      filePath,
      name: 'file',
      success: (res) => {
        try {
          const response = JSON.parse(res.data)
          if (response.code !== 200) {
            console.log(response)
            reject(new Error('上传失败'))
          } else {
            resolve(response)
          }
        } catch (error) {
          console.error('上传异常', error)
          uni.showToast({
            title: '上传异常,请刷新重试',
            icon: 'none',
          })
          reject(error)
        }
      },
      fail: (fail) => {
        console.error('上传异常', fail)
        uni.showToast({
          title: '上传失败,请刷新重试',
          icon: 'none',
        })
        reject(fail)
      },
    })
  })
}

export const getCaptchaData = (id: string) => {
  return request({
    url: '/api/common/clickCaptcha',
    method: 'GET',
    data: {
      id,
    },
  })
}

export const getCaptchaCodeApi = (id: string) => {
  return request({
    url: '/api/common/captcha',
    method: 'GET',
    data: {
      id,
    },
    responseType: 'arraybuffer',
  })
}

export const checkClickCaptcha = (id: string, info: string, unset: boolean) => {
  return request({
    url: '/api/common/checkClickCaptcha',
    method: 'POST',
    data: {
      id,
      info,
      unset,
    },
  })
}

export const sendSmsCode = (data: {
  mobile: string
  template_code: string
  captcha_id: string
  captcha_info: string
  click?: boolean
  password?: string
}) => {
  return request({
    url: '/common/sendSmsCode',
    method: 'POST',
    data,
  })
}

export const getAreaDataApi = () => {
  return request({
    url: '/common/area',
    method: 'GET',
  })
}
